/*
 *    Copyright (c) 2018-2025, proj All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the proj developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: proj
 */

package com.ykht.proj.coupon.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ykht.proj.admin.api.entity.SysUser;
import com.ykht.proj.admin.api.feign.RemoteUserService;
import com.ykht.proj.common.core.constant.CacheConstants;
import com.ykht.proj.common.core.util.R;
import com.ykht.proj.common.security.util.SecurityUtils;
import com.ykht.proj.coupon.Enum.DistributionTypeEnum;
import com.ykht.proj.coupon.Enum.LookRoleTypeEnum;
import com.ykht.proj.coupon.entity.*;
import com.ykht.proj.coupon.service.*;
import com.ykht.proj.coupon.vo.FxRewardVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 服务员奖励记录表(待定)
 *
 * @author proj code generator
 * @date 2021-02-01 19:00:17
 */
@RestController
@AllArgsConstructor
@RequestMapping("/fxreward")
@Api(value = "fxreward", tags = "服务员奖励记录表(待定)管理")
public class FxRewardController {

	private final FxRewardService fxRewardService;

	/**
	 * 用户 服务 Api
	 */
	private final RemoteUserService remoteUserService;
	/**
	 * 饭友 服务
	 */
	private final FxBrandPersonService fxBrandPersonService;
	/**
	 * C端用户
	 */
	private final CnPersonService cnPersonService;
	/**
	 * 服务员 服务
	 */
	private final FxWaiterExtService fxWaiterExtService;
	/**
	 * 门店 服务
	 */
	private final CnShopService cnShopService;
	/**
	 * 缓存Api
	 */
	private final RedisTemplate redisTemplate;

	/**
	 * 记录详情的 分销明细 分页查询
	 *
	 * @param page       分页对象
	 * @param fxRewardVo 服务员奖励记录表(待定)
	 * @return //	@PreAuthorize("@pms.hasPermission('coupon_fxreward_view')")
	 */
	@ApiOperation(value = "记录详情的 分销明细 分页查询", notes = "记录详情的 分销明细 分页查询")
	@GetMapping("/getFxRewardPage")
	public R<IPage<FxRewardVo>> getFxRewardPage(Page page, FxRewardVo fxRewardVo) {
		fxRewardVo.setLoginRoleType(SecurityUtils.getUser().getUserType());
		IPage<FxRewardVo> personVoIPage = fxRewardService.findPage(page, fxRewardVo);
		if (DistributionTypeEnum.DISTRIBUTION_TYPE_2.getValue().equals(fxRewardVo.getDistributionType())) {
			List<FxRewardVo> records = personVoIPage.getRecords();
			if (records.size() > 0) {
				List<Long> ids = records.stream().map(itme -> Long.valueOf(itme.getLoginId())).collect(Collectors.toList());
				ids.stream().distinct().collect(Collectors.toList());
				List<SysUser> userList = remoteUserService.userByIds(ids);
				records.stream().forEach(itme -> {
					userList.stream().forEach(user -> {
						if (itme.getLoginId().equals(Long.valueOf(user.getUserId())) && itme.getRewardRoleType().equals(1)) {
							itme.setUsername(user.getUsername());
							itme.setNickName(user.getNickName());
						} else if (itme.getLoginId().equals(Long.valueOf(user.getUserId())) && itme.getRewardRoleType().equals(2)){
							itme.setUsername(user.getUsername());
							itme.setNickName(user.getNickName());
						}
					});
				});
				personVoIPage.setRecords(records);
			}
		}
		if (DistributionTypeEnum.DISTRIBUTION_TYPE_0.getValue().equals(fxRewardVo.getDistributionType())) {
			List<FxRewardVo> records = personVoIPage.getRecords();
			if (records.size() > 0) {
				List<Long> ids = records.stream().map(itme -> Long.valueOf(itme.getLoginId())).collect(Collectors.toList());
				List<SysUser> userList = remoteUserService.userByIds(ids);
				records.stream().forEach(itme -> {
					userList.stream().forEach(user -> {
						if (itme.getLoginId().equals(Long.valueOf(user.getUserId()))) {
							itme.setUsername(user.getUsername());
							itme.setNickName(user.getNickName());
						}
					});
				});
				personVoIPage.setRecords(records);
			}
		}
		return R.ok(personVoIPage);
	}


	/**
	 * 记录详情的分销明细  统计
	 *
	 * @param fxRewardVo 服务员奖励记录表(待定)
	 * @return
	 */
	@ApiOperation(value = "记录详情的分销明细  统计", notes = "记录详情的分销明细  统计")
	@GetMapping("/getFxRewardCount")
	public R<FxRewardVo> getFxRewardCount(FxRewardVo fxRewardVo) {
		fxRewardVo.setLoginRoleType(SecurityUtils.getUser().getUserType());

		fxRewardVo.setDistributionType(DistributionTypeEnum.DISTRIBUTION_TYPE_0.getValue());
		FxRewardVo fxReward1 = fxRewardService.getSumByMoney(fxRewardVo);
		if (null != fxReward1) {
			fxRewardVo.setInvitationCommissionCount(fxReward1.getDistributionTypeMoney());
		}

		fxRewardVo.setDistributionType(DistributionTypeEnum.DISTRIBUTION_TYPE_1.getValue());
		FxRewardVo fxReward2 = fxRewardService.getSumByMoney(fxRewardVo);
		if (null != fxReward2) {
			fxRewardVo.setForwardCommissionCount(fxReward2.getDistributionTypeMoney());
		}
		fxRewardVo.setDistributionType(DistributionTypeEnum.DISTRIBUTION_TYPE_2.getValue());
		FxRewardVo fxReward3 = fxRewardService.getSumByMoney(fxRewardVo);
		if (null != fxReward3) {
			fxRewardVo.setCouponCommissionCount(fxReward3.getDistributionTypeMoney());
		}
		if (LookRoleTypeEnum.LOOK_ROLE_TYPE_1.getValue().equals(fxRewardVo.getLookRoleType())) {
			// 核销优惠券统计
			fxRewardVo.setCouponCount(fxRewardService.count(new QueryWrapper<FxReward>()
					.lambda().eq(FxReward::getType, DistributionTypeEnum.DISTRIBUTION_TYPE_2.getValue())
					.eq(FxReward::getWaiterId, fxRewardVo.getWaiterId()).eq(FxReward::getDelFlag, 0)));
			// 转发统计
			fxRewardVo.setForwardCount(fxRewardService.count(new QueryWrapper<FxReward>()
					.lambda().eq(FxReward::getType, DistributionTypeEnum.DISTRIBUTION_TYPE_1.getValue())
					.eq(FxReward::getWaiterId, fxRewardVo.getWaiterId()).eq(FxReward::getDelFlag, 0)));
			// 邀请统计
			fxRewardVo.setInvitationCount(fxRewardService.count(new QueryWrapper<FxReward>()
					.lambda().eq(FxReward::getType, DistributionTypeEnum.DISTRIBUTION_TYPE_0.getValue())
					.eq(FxReward::getWaiterId, fxRewardVo.getWaiterId()).eq(FxReward::getDelFlag, 0)));
		} else if (LookRoleTypeEnum.LOOK_ROLE_TYPE_2.getValue().equals(fxRewardVo.getLookRoleType())) {
			// 核销优惠券统计
			fxRewardVo.setCouponCount(fxRewardService.count(new QueryWrapper<FxReward>()
					.lambda().eq(FxReward::getType, DistributionTypeEnum.DISTRIBUTION_TYPE_2.getValue())
					.eq(FxReward::getShopId, fxRewardVo.getShopId()).eq(FxReward::getDelFlag, 0)));
			// 转发统计
			fxRewardVo.setForwardCount(fxRewardService.count(new QueryWrapper<FxReward>()
					.lambda().eq(FxReward::getType, DistributionTypeEnum.DISTRIBUTION_TYPE_1.getValue())
					.eq(FxReward::getShopId, fxRewardVo.getShopId()).eq(FxReward::getDelFlag, 0)));
			// 邀请统计
			fxRewardVo.setInvitationCount(fxRewardService.count(new QueryWrapper<FxReward>()
					.lambda().eq(FxReward::getType, DistributionTypeEnum.DISTRIBUTION_TYPE_0.getValue())
					.eq(FxReward::getShopId, fxRewardVo.getShopId()).eq(FxReward::getDelFlag, 0)));
		} else if (LookRoleTypeEnum.LOOK_ROLE_TYPE_3.getValue().equals(fxRewardVo.getLookRoleType())) {
			// 核销优惠券统计
			fxRewardVo.setCouponCount(fxRewardService.count(new QueryWrapper<FxReward>()
					.lambda().eq(FxReward::getType, DistributionTypeEnum.DISTRIBUTION_TYPE_2.getValue())
					.eq(FxReward::getBrandId, fxRewardVo.getBrandId()).eq(FxReward::getDelFlag, 0)));
			// 转发统计
			fxRewardVo.setForwardCount(fxRewardService.count(new QueryWrapper<FxReward>()
					.lambda().eq(FxReward::getType, DistributionTypeEnum.DISTRIBUTION_TYPE_1.getValue())
					.eq(FxReward::getBrandId, fxRewardVo.getBrandId()).eq(FxReward::getDelFlag, 0)));
			// 邀请统计
			fxRewardVo.setInvitationCount(fxRewardService.count(new QueryWrapper<FxReward>()
					.lambda().eq(FxReward::getType, DistributionTypeEnum.DISTRIBUTION_TYPE_0.getValue())
					.eq(FxReward::getBrandId, fxRewardVo.getBrandId()).eq(FxReward::getDelFlag, 0)));
		} else if (LookRoleTypeEnum.LOOK_ROLE_TYPE_4.getValue().equals(fxRewardVo.getLookRoleType())) {
			// 核销优惠券统计
			fxRewardVo.setCouponCount(fxRewardService.count(new QueryWrapper<FxReward>()
					.lambda().eq(FxReward::getType, DistributionTypeEnum.DISTRIBUTION_TYPE_2.getValue())
					.eq(FxReward::getCompanyId, fxRewardVo.getCompanyId()).eq(FxReward::getDelFlag, 0)));
			// 转发统计
			fxRewardVo.setForwardCount(fxRewardService.count(new QueryWrapper<FxReward>()
					.lambda().eq(FxReward::getType, DistributionTypeEnum.DISTRIBUTION_TYPE_1.getValue())
					.eq(FxReward::getCompanyId, fxRewardVo.getCompanyId()).eq(FxReward::getDelFlag, 0)));
			// 邀请统计
			fxRewardVo.setInvitationCount(fxRewardService.count(new QueryWrapper<FxReward>()
					.lambda().eq(FxReward::getType, DistributionTypeEnum.DISTRIBUTION_TYPE_0.getValue())
					.eq(FxReward::getCompanyId, fxRewardVo.getCompanyId()).eq(FxReward::getDelFlag, 0)));
		}
		return R.ok(fxRewardVo);
	}


	/**
	 * 获取饭友详情
	 *
	 * @param id 饭友ID
	 * @return
	 */
	@ApiOperation(value = "分销记录-分销详情-饭友详情", notes = "分销记录-分销详情-饭友详情")
	@GetMapping("/getFanYouDetails")
	public R<CnPerson> getFanYouDetails(Long id) {
		FxBrandPerson fxBrandPerson = fxBrandPersonService.getById(id);
		return R.ok(cnPersonService.getById(fxBrandPerson.getPerId()));
	}

	/**
	 * 饭友详情的 饭友列表 分页
	 *
	 * @param page
	 * @param fxRewardVo
	 * @return
	 */
	@ApiOperation(value = "饭友详情的 饭友列表 分页", notes = "饭友详情的 饭友列表 分页")
	@GetMapping("/getFanYouDetailsListPage")
	public R<IPage<FxRewardVo>> getFanYouDetailsListPage(Page page, FxRewardVo fxRewardVo) {
		IPage<FxRewardVo> personVoIPage = new Page<>();
		if (null != fxRewardVo.getNickName() && !"".equals(fxRewardVo.getNickName())) {
			List<SysUser> userList = remoteUserService.findByNickName(fxRewardVo.getNickName());
			if (userList.size() > 0) {
				List<Long> userIds = new ArrayList<>();
				userList.stream().forEach(itme -> {
					userIds.add(Long.valueOf(itme.getUserId()));
				});
				fxRewardVo.setUserIds(userIds);
			} else {
				return R.ok(personVoIPage);
			}
		}
		personVoIPage = fxRewardService.getFanYouDetailsListPage(page, fxRewardVo);
		List<FxRewardVo> records = personVoIPage.getRecords();
		if (records.size() > 0) {
			List<Long> ids = new ArrayList<>();
			records.stream().forEach(itme -> {
				ids.add(itme.getWaiterId());
			});
			List<FxWaiterExt> fxWaiterExts = fxWaiterExtService.list(new QueryWrapper<FxWaiterExt>().lambda().in(FxWaiterExt::getId, ids));
			List<Long> userId = new ArrayList<>();
			fxWaiterExts.stream().forEach(itme -> {
				userId.add(itme.getLoginId());
			});
			List<SysUser> userList = remoteUserService.userByIds(userId);
			records.stream().forEach(itme -> {
				userList.stream().forEach(user -> {
					if (itme.getLoginId().equals(Long.valueOf(user.getUserId()))) {
						itme.setUsername(user.getUsername());
						itme.setNickName(user.getNickName());
					}
				});
			});
			personVoIPage.setRecords(records);
		}
		return R.ok(personVoIPage);
	}

	/**
	 * 获取饭友详情 的 核销明细 统计（核销佣金 和 核销次数）
	 *
	 * @param fxRewardVo
	 * @return
	 */
	@ApiOperation(value = "获取饭友详情 的 核销明细 统计（核销佣金 和 核销次数）", notes = "获取饭友详情 的 核销明细 统计（核销佣金 和 核销次数）")
	@GetMapping("/getWriteDetailsCount")
	public R<FxRewardVo> getWriteDetailsCount(FxRewardVo fxRewardVo) {
		FxRewardVo personVoIPage = fxRewardService.getWriteDetailsCount(fxRewardVo);
		return R.ok(personVoIPage);
	}

	/**
	 * 获取饭友详情 的 核销明细 分页
	 *
	 * @param page
	 * @param fxRewardVo
	 * @return
	 */
	@ApiOperation(value = "获取饭友详情 的 核销明细 分页", notes = "获取饭友详情 的 核销明细 分页")
	@GetMapping("/getWriteDetailsListPage")
	public R<IPage<FxRewardVo>> getWriteDetailsListPage(Page page, FxRewardVo fxRewardVo) {
		IPage<FxRewardVo> personVoIPage = fxRewardService.getWriteDetailsListPage(page, fxRewardVo);
		List<FxRewardVo> records = personVoIPage.getRecords();
		if (records.size() > 0) {
			List<Long> ids = new ArrayList<>();
			records.stream().forEach(itme -> {
				ids.add(itme.getWaiterId());
			});
			List<FxWaiterExt> fxWaiterExts = fxWaiterExtService.list(new QueryWrapper<FxWaiterExt>().lambda().in(FxWaiterExt::getId, ids));
			List<Long> userId = new ArrayList<>();
			fxWaiterExts.stream().forEach(itme -> {
				userId.add(itme.getLoginId());
			});
			List<SysUser> userList = remoteUserService.userByIds(userId);
			records.stream().forEach(itme -> {
				userList.stream().forEach(user -> {
					if (itme.getLoginId().equals(Long.valueOf(user.getUserId()))) {
						itme.setUsername(user.getUsername());
						itme.setNickName(user.getNickName());
					}
				});
			});
			personVoIPage.setRecords(records);
		}
		return R.ok(personVoIPage);
	}

	/**
	 * 获取音效提醒
	 *
	 * @return
	 */
	@ApiOperation(value = "获取音效提醒", notes = "获取音效提醒")
	@GetMapping("/getSoundRemind")
	public R getSoundRemind() {
		FxWaiterExt waiterExt = new FxWaiterExt().selectOne(Wrappers.lambdaQuery(FxWaiterExt.class)
				.eq(FxWaiterExt::getLoginId, SecurityUtils.getUserId())
				.eq(FxWaiterExt::getWorkState, 1).eq(FxWaiterExt::getDelFlag, 0));
		if (waiterExt != null){
			Object o = redisTemplate.opsForValue().get(CacheConstants.SOUND_REMIND + waiterExt.getId());
			redisTemplate.delete(CacheConstants.SOUND_REMIND + waiterExt.getId());
			return R.ok(o);
		}
		return R.ok(null);
	}

}
